package eu.ict_omelette.mashup.canonicalmodel.test;

import eu.ict_omelette.mashup.adapters.pipes.Canonical2Json;
import eu.ict_omelette.mashup.adapters.pipes.PipesAdapter;
import eu.ict_omelette.mashup.canonicalmodel.CanonicalMashup;
import eu.ict_omelette.mashup.canonicalmodel.Component;
import eu.ict_omelette.mashup.canonicalmodel.Dataflow;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URI;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author guybrush
 */
public class DatabaseFilling {

    static final String insert = "INSERT INTO CompCo (srcComp, conf, usage) VALUES ",
                        update = "UPDATE CompCo SET usage = ",
                        usage = "SELECT usage FROM CompCo ",
                        objs_file = "objs.csv",

                        Pipes_Path = "/tmp/sport_news",
                        Seri_Path = "/tmp/serialized";

    public static void main(String args[]){

        Integer parsed_count = 0,
                objs_count = 0;

        Connection conn = null;
        BufferedReader reader = null;

        try{
            Class.forName("org.sqlite.JDBC");
            conn = DriverManager.getConnection("jdbc:sqlite:bayatest.sqlite");
            Statement stat = conn.createStatement();            
            

            String dirPath = Seri_Path;
            String[] children = new File(dirPath).list();

            if(children == null || children.length < 1)
            { System.out.println("Directory does not exists or it is empty"); System.exit(1); }

            for(int i = 0; i < children.length; i++)
            {
                String filename = children[i], filepath = "";
                if(filename.contains("pipe") || filename.contains(".ser")) filepath = dirPath + "/" + filename; else break;

                CanonicalMashup cm = null;
                if (dirPath.equals(Pipes_Path))
                {
                    URI uri = new File(filepath).toURI();
                    PipesAdapter adapter = new PipesAdapter();

                    adapter.loadSourceMashupModel(uri);
                    cm = adapter.getCanonicalMashup();
                }
                if (dirPath.equals(Seri_Path)) cm = CanonicalMashup.unserialize(filepath);

                reader = new BufferedReader(new FileReader(new File(objs_file))); String obj = reader.readLine();
                while(obj != null)
                {
                    if (i == 0) objs_count++;
                    Boolean exit = false;

                    ArrayList<Component> comps = new ArrayList<Component>();
                    ArrayList<Dataflow> wires = new ArrayList<Dataflow>();
                    for (Iterator<Component> comp_it = cm.getComponents(); comp_it.hasNext() && !exit;)
                    {
                        Component comp = comp_it.next();
                        if (comp.getType().equals(obj))
                        {
                            comps.add(comp);
                            for (Iterator<Dataflow> wire_it = cm.getDataFlows(); wire_it.hasNext();) {
                                Dataflow wire = wire_it.next();

                                if (wire.getFromComponent().getId().equals(comp.getId()))
                                { comps.add(wire.getToComponent()); exit = true; }
                                else if (wire.getToComponent().getId().equals(comp.getId()))
                                { comps.add(wire.getFromComponent()); exit = true; }

                                if (exit) { wires.add(wire); break; }
                            }
                        }
                    }

                    if (wires.size() > 0 && comps.size() > 1)
                    {
                        parsed_count++;

                        String conf = "{" + Canonical2Json.converteDataFlows(wires.iterator())
                                   + "," + Canonical2Json.converteComponents(comps.iterator()) + "}";

                        Integer u = getUsage(stat, obj, conf);
                        if (u < 1) addRow(stat, obj, conf);
                        else setUsage(stat, obj, conf, u + 1);
                    }

                    obj = reader.readLine();
                }
                reader.close();
            }
            System.out.println("Parsed wires: " + parsed_count + " on " + children.length + 
                    " files and " + objs_count + " objects.");
        }catch(Exception e){
            e.printStackTrace(); }
    }

    static private String getDefWhereStmt(String src, String conf)
    { return " WHERE srcComp = '" + src + "' AND conf = '" + conf + "'"; }

    static private void addRow(Statement stmt, String src, String conf) throws SQLException
    { stmt.execute(insert + "('" + src + "','" + conf + "',1)"); }
    static private void incUsage(Statement stmt, String src, String conf) throws SQLException
    { setUsage(stmt, src, conf, (getUsage(stmt, src, conf) + 1)); }
    static private void setUsage(Statement stmt, String src, String conf, Integer usage) throws SQLException
    { stmt.executeUpdate(update + "'" + String.valueOf(usage) + "'" + getDefWhereStmt(src, conf)); }
    static private Integer getUsage(Statement stmt, String src, String conf) throws SQLException
    { ResultSet res = stmt.executeQuery(usage + getDefWhereStmt(src, conf)); if (res.next()) return res.getInt(1); return 0; }
}
